#include <unistd.h>

#include "base/notification.h"
#include "gtest/gtest.h"
#include "thread/executor.h"
#include "util/time.h"

void NotifyFun(int delay, Notification* notification) {
  if (delay > 0) {
    sleep(delay);
  }
  notification->Notify();
}

TEST(Notification, NotifyImmediately) {
  DefaultExecutor executor(1);
  Notification notification;
  int64 t = GetCurrentTime();
  executor.Add(NewCallback(&NotifyFun, 0, &notification));
  notification.WaitForNotification();
  int64 delay = GetCurrentTime() - t;
  EXPECT_LT(delay / 1000000, 1);
}

TEST(Notification, NotifyAfterThreeSec) {
  DefaultExecutor executor(1);
  Notification notification;
  int64 t = GetCurrentTime();
  executor.Add(NewCallback(&NotifyFun, 3, &notification));
  notification.WaitForNotification();
  int64 delay = GetCurrentTime() - t;
  EXPECT_GE(delay / 1000000, 2);
}

TEST(Notification, NotifyAfterThreeSec2) {
  DefaultExecutor executor(1);
  Notification notification;
  int64 t = GetCurrentTime();
  executor.AddAfter(3, NewCallback(&NotifyFun, 0, &notification));
  notification.WaitForNotification();
  int64 delay = GetCurrentTime() - t;
  EXPECT_GE(delay / 1000000, 2);
}
